package com.hunmengwl.oauth.common.config;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author Hun
 * @ClassName AdminInterceptor
 * @description TODO 用于认证授权
 * @date 2020/6/21 20:25
 * @Version 1.0
 */
@Component
@Log4j2
public class AdminInterceptor implements Filter {

    private final String password = "qwert123";

    private static final String[] URL = new String[]{"/error/404","/lock","/favicon.ico"};

    private static final List<String> URL_LIST = Arrays.asList(URL);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        if(URL_LIST.contains(httpServletRequest.getRequestURI())){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        HttpSession session = httpServletRequest.getSession();
        String userSession = (String) session.getAttribute("user");
        if(StringUtils.isNotEmpty(userSession)){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        String user = httpServletRequest.getParameter("user");
        if(StringUtils.equals(password, user)){
            session.setAttribute("user","user");
        }else {
            response(httpServletResponse);
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    /**
     * 这个方法之后可以放到HttpUtils中
     *
     * @param response
     */
    private void response(HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        try {
            response.sendRedirect("/error/404");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
